Skip to content

Conversation

@saifsultanc
Copy link
Contributor

Context

⛑️ Ticket(s): https://secure.helpscout.net/conversation/2951970232/84219

Summary

Add support for grouping file upload fields in the GPFUP Count Files snippet. Allow defining multiple groups and assigning each group’s count to a different number field.

https://www.loom.com/share/2328e327125844bebdcabf7c9baaabca

@coderabbitai
Copy link

coderabbitai bot commented Jun 2, 2025

"""

Walkthrough

A new JavaScript module is added to dynamically count files uploaded through grouped file upload fields in a Gravity Forms form using the Gravity Perks File Upload Pro plugin. The script updates designated number fields with the total count of files uploaded in their associated groups, responding in real time to file upload changes.

Changes

File(s) Change Summary
gp-file-upload-pro/gpfup-count-files-groups.js New script to count uploaded files across grouped fields and update associated number fields in real time

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Form (DOM)
    participant GPFUP Plugin
    participant Script

    User->>Form (DOM): Uploads/removes file(s)
    Form (DOM)->>GPFUP Plugin: Handles file upload
    GPFUP Plugin-->>Script: Emits file set event (Vuex mutation)
    Script->>Script: Recalculate total files for each group
    Script->>Form (DOM): Update number field(s) with new count
Loading

Suggested reviewers

  • veryspry
    """

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 68c80f2 and 5e02037.

📒 Files selected for processing (1)
  • gp-file-upload-pro/gpfup-count-files-groups.js (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • gp-file-upload-pro/gpfup-count-files-groups.js
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Danger JS
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (6)
gp-file-upload-pro/gpfup-count-files-groups.js (6)

7-7: Consider using modern JavaScript declarations.

The code works correctly with the global GFFORMID variable. Consider using const instead of var for better code quality and to prevent accidental reassignment.

-var formId = GFFORMID;
+const formId = GFFORMID;

9-14: Clear configuration structure.

The mapping configuration is well-structured and documented. Consider using const for immutable configuration data.

-var countMapping = {
+const countMapping = {

25-34: Efficient reverse lookup construction.

The logic correctly builds the reverse mapping using functional programming patterns. Consider using const and modern destructuring syntax.

-var uploadToCountMap = {};
-Object.entries(countMapping).forEach(function ([countFieldID, uploadFieldIDs]) {
+const uploadToCountMap = {};
+Object.entries(countMapping).forEach(([countFieldID, uploadFieldIDs]) => {
-	uploadFieldIDs.forEach(function (uploadFieldID) {
+	uploadFieldIDs.forEach((uploadFieldID) => {

36-48: Improve robustness with optional chaining and error handling.

The core logic is correct. Consider using optional chaining as suggested by static analysis and add error handling for missing DOM elements.

 function updateAllCountFields() {
-	Object.entries(countMapping).forEach(function ([countFieldID, uploadFieldIDs]) {
-		var total = uploadFieldIDs.reduce(function (sum, uploadFieldID) {
-			var key = 'GPFUP_' + formId + '_' + uploadFieldID;
-			var store = window[key] && window[key].$store;
+	Object.entries(countMapping).forEach(([countFieldID, uploadFieldIDs]) => {
+		const total = uploadFieldIDs.reduce((sum, uploadFieldID) => {
+			const key = 'GPFUP_' + formId + '_' + uploadFieldID;
+			const store = window[key]?.$store;
 			return sum + (store ? (store.state.files.length || 0) : 0);
 		}, 0);
 
-		var selector = '#input_' + formId + '_' + countFieldID;
-		jQuery(selector).val(total).change();
+		const selector = '#input_' + formId + '_' + countFieldID;
+		const $field = jQuery(selector);
+		if ($field.length) {
+			$field.val(total).change();
+		}
 	});
 }
🧰 Tools
🪛 Biome (1.9.4)

[error] 41-41: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


50-63: Efficient event subscription with proper filtering.

The subscription logic correctly identifies relevant fields and listens for the appropriate mutation type. Consider modernizing the syntax for consistency.

-gpfupInstances.forEach(function (key) {
-	var parts = key.split('_');
-	var fieldID = parseInt(parts[2]); // GPFUP_formId_fieldId
-	var store = window[key].$store;
+gpfupInstances.forEach((key) => {
+	const parts = key.split('_');
+	const fieldID = parseInt(parts[2]); // GPFUP_formId_fieldId
+	const store = window[key].$store;
 
 	if (uploadToCountMap[fieldID]) {
-		store.subscribe(function (mutation, state) {
+		store.subscribe((mutation, state) => {
 			if (mutation.type === 'SET_FILES') {
 				updateAllCountFields();
 			}
 		});
 	}
 });

1-67: Overall assessment: Good functionality with critical syntax fix needed.

The script implements a useful feature for counting files across grouped upload fields. However, there's a critical syntax error that prevents execution. Consider these improvements:

  1. Critical: Fix the illegal return statement (line 22)
  2. Recommended: Use modern JavaScript syntax (const/let, arrow functions, optional chaining)
  3. Enhancement: Add comprehensive error handling for missing DOM elements and store instances
  4. Documentation: Consider adding JSDoc comments for the main function

Would you like me to provide a complete refactored version that addresses all these points and follows modern JavaScript best practices?

🧰 Tools
🪛 Biome (1.9.4)

[error] 22-22: Illegal return statement outside of a function

(parse)


[error] 41-41: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e83c22b and a8200b0.

📒 Files selected for processing (1)
  • gp-file-upload-pro/gpfup-count-files-groups.js (1 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
gp-file-upload-pro/gpfup-count-files-groups.js

[error] 22-22: Illegal return statement outside of a function

(parse)


[error] 41-41: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

🔇 Additional comments (2)
gp-file-upload-pro/gpfup-count-files-groups.js (2)

1-6: LGTM!

Clear documentation header with helpful links to both general documentation and specific instruction video.


65-66: LGTM!

Proper initialization to ensure counts are accurate on page load.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (2)
gp-file-upload-pro/gpfup-count-files-groups.js (2)

9-14: Enhance configuration documentation for better usability.

Consider adding more detailed documentation to help users understand how to configure the mapping correctly.

Add more comprehensive documentation:

 // Map count field IDs to arrays of file upload field IDs
+// Each key is a Number Field ID that will display the count
+// Each value is an array of File Upload Field IDs to count files from
+// Example: Field 5 will show total files from upload fields 1, 3, and 4
 var countMapping = {
-	// Add more mappings if needed
+	// Add more mappings as needed: countFieldID: [uploadFieldID1, uploadFieldID2, ...]
 };

32-44: Core update logic is solid, consider modern syntax improvement.

The function correctly calculates file counts and updates the DOM. The logic handles edge cases well.

Consider using optional chaining for cleaner code (addresses static analysis hint):

-		var store = window[key] && window[key].$store;
+		var store = window[key]?.$store;

This makes the code more readable while maintaining the same safety guarantees.

🧰 Tools
🪛 Biome (1.9.4)

[error] 37-37: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a8200b0 and 28d6ad0.

📒 Files selected for processing (1)
  • gp-file-upload-pro/gpfup-count-files-groups.js (1 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
gp-file-upload-pro/gpfup-count-files-groups.js

[error] 37-37: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

🔇 Additional comments (5)
gp-file-upload-pro/gpfup-count-files-groups.js (5)

1-8: Well-documented file header with clear context.

The documentation header provides excellent context with links to documentation and instruction video. The formId declaration follows standard Gravity Forms patterns.


16-19: Efficient GPFUP instance discovery implementation.

The logic correctly identifies all GPFUP instances for the form using a clean pattern matching approach.


21-30: Well-implemented reverse lookup mapping.

The reverse lookup logic correctly handles the many-to-many relationship between upload fields and count fields. The implementation properly accounts for multiple count fields that might depend on the same upload field.


46-61: Efficient event subscription with proper filtering.

The subscription logic is well-optimized, only listening to relevant upload fields and the appropriate mutation type. The conditional check prevents unnecessary processing when no GPFUP instances exist.


63-64: Proper initialization ensures accurate counts on page load.

The initial function call correctly sets up the count fields when the page loads.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (3)
gp-file-upload-pro/gpfup-count-files-groups.js (3)

17-17: Use consistent variable declarations.

The code uses var here but const elsewhere. For consistency and better scoping, use const since this variable is not reassigned.

-var gpfupInstances = Object.keys(window).filter(function (key) {
+const gpfupInstances = Object.keys(window).filter(function (key) {

37-37: Use optional chaining for cleaner code.

The static analysis tool correctly identified that this can be simplified using optional chaining.

-		const store = window[key] && window[key].$store;
+		const store = window[key]?.$store;
🧰 Tools
🪛 Biome (1.9.4)

[error] 37-37: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


49-67: Good implementation with minor improvement suggestion.

The subscription logic is well-implemented and efficiently uses the reverse lookup to only subscribe to relevant fields. The initial count call ensures proper state on page load.

Consider adding error handling for store subscription:

		if (uploadToCountMap[fieldID]) {
-			store.subscribe((mutation, state) => {
-				if (mutation.type === 'SET_FILES') {
-					updateAllCountFields();
-				}
-			});
+			try {
+				store.subscribe((mutation, state) => {
+					if (mutation.type === 'SET_FILES') {
+						updateAllCountFields();
+					}
+				});
+			} catch (error) {
+				console.error('Failed to subscribe to store:', error);
+			}
		}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 28d6ad0 and 28c116c.

📒 Files selected for processing (1)
  • gp-file-upload-pro/gpfup-count-files-groups.js (1 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
gp-file-upload-pro/gpfup-count-files-groups.js

[error] 37-37: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

🔇 Additional comments (1)
gp-file-upload-pro/gpfup-count-files-groups.js (1)

9-14: LGTM! Well-structured configuration mapping.

The configuration object is clearly documented and provides a flexible way to define field relationships. The inline comments make it easy to understand the mapping structure.

`gpfup-count-files-groups.js`: Added snippet to count files in groups.

`gpfup-count-files-groups.js`: Added snippet to count files in groups.
@saifsultanc saifsultanc force-pushed the saif/add/84219-add-gpfup-count-files-groups branch from 69a8201 to 68c80f2 Compare June 2, 2025 07:25
Copy link
Contributor

@veryspry veryspry left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@saifsultanc one suggestion / question!

if (uploadToCountMap[fieldID]) {
store.subscribe((mutation, state) => {
if (mutation.type === 'SET_FILES') {
updateAllCountFields();
Copy link
Contributor

@veryspry veryspry Jun 13, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since uploadToCountMap[fieldID] has an array of all count fields that need updating, what do you think about passing that as a param to updateAllCountFields() to avoid recalculating anything unnecessary count fields?

It would also need to account for the initial "update" for all count fields then too if making this suggested addition

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done!

@saifsultanc saifsultanc requested a review from veryspry June 13, 2025 17:04
@saifsultanc saifsultanc merged commit bcd4e32 into master Jun 14, 2025
4 of 5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

3 participants